/*
package aspn.office.szga;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import com.bos.common.ASPNConstans;
import com.bos.common.DateFormat2;
import com.bos.common.FileUtil2;
import com.bos.msg2.BOSCustomerInfo;
import com.bos.msg2.ServiceCommon;
import com.eos.system.utility.StringUtil;
import com.primeton.btp.api.core.logger.ILogger;
import com.primeton.btp.api.core.logger.LoggerFactory;

import aspn.office.RequestHandler;
import aspn.util.ZipFileUtil2;

*
 * @description 深圳公安的请求文件
 * @author huangcan
 * @date created in: 2019年7月16日 上午9:27:43


public class SZGARequestHandler implements RequestHandler {
    private static final ILogger LOGGER = LoggerFactory.getLogger(SZGARequestHandler.class);
    private static String path = "D:/share_cfbp/aspn/szga";
    private static String resolvePath = path + File.separator + "resolve";//解析路径
    private static String errorPath = path + File.separator + "error";//解析路径
    private static String queryReqPath =  path + File.separator + "request";//查询执行器的文件路径
    private static String tempPath = path + File.separator + "temp";

    private ConcurrentHashMap<String, Map<String, String>> checkDataMap = new ConcurrentHashMap<String, Map<String, String>>();
    private static String symbol = "|";
    private BufferedReader read = null;
    private BufferedWriter write = null;


    public File format(File requestFile) {
        try {
            FileUtil2.checkFileIsHave(requestFile);//判断来盘请求文件是否存在
            //来盘请求文件名
            String recvZipFileName = requestFile.getName();
            if(!SZGACommon.checkReqQueryFileName(recvZipFileName)){
                LOGGER.debug("["+requestFile.getName()+"]不是深圳公安的来盘文件！");
                //将这个文件移动至错误目录
                FileUtil2.moveFileToDirectory(requestFile, new File(errorPath), true);
                return null;
            }
            LOGGER.debug("开始解压深圳公安查控申请压缩文件，文件名：" + recvZipFileName);
            //获取查控申请压缩文件名的前缀
            String zipFileNamePrefix = recvZipFileName.substring(0, recvZipFileName.lastIndexOf("."));
            //开始解压文件
            String zipResoPath = (resolvePath+File.separator+zipFileNamePrefix);
            ZipFileUtil2.unZipFile(requestFile, zipResoPath, ASPNConstans.ENCODE_GBK);
            LOGGER.debug("解压深圳公安查控申请压缩文件成功，解压路径：" + zipResoPath);

            //判断法律文书信息文件是否齐全-LI25、LI26、LI27，文件的结尾为.jpg/PDF
            String fileNameLI25Prefix = "LI25" + zipFileNamePrefix;
            String fileNameLI26Prefix = "LI26" + zipFileNamePrefix;
            String fileNameLI27Prefix = "LI27" + zipFileNamePrefix;
            boolean li25Flag = SZGACommon.checkCertificateFile(fileNameLI25Prefix, zipResoPath);
            boolean li26Flag = SZGACommon.checkCertificateFile(fileNameLI26Prefix, zipResoPath);
            boolean li27Flag = SZGACommon.checkCertificateFile(fileNameLI27Prefix, zipResoPath);

            if(li25Flag && li26Flag && li27Flag){
                //查控法律文件信息文件齐全
                //获取查控文件list，可以一个查控文件，也可能是多个查控文件。
                List<File> queryFileList = SZGACommon.getInvestigateFileList(zipFileNamePrefix, zipResoPath );
                if(queryFileList==null || queryFileList.size()<=0){
                    LOGGER.error("没有找到查控文件，请确认文件["+recvZipFileName+"]");
                    FileUtil2.moveFileToDirectory(requestFile, new File(errorPath), true);
                    return null;
                }
                LOGGER.debug("获取查控文件成功，查控文件个数["+queryFileList.size()+"]");
                //开始处理查控文件
                startHandler(queryFileList);
                //处理结束，将数据写入临时文件
                try {
                    FileUtil2.createDirectories(tempPath);
                    FileUtil2.createDirectories(queryReqPath);
                    File tempFile = new File(tempPath + File.separator + zipFileNamePrefix + ".temp");
                    //查询执行器的文件
                    String reqQueryFileName = "SZGA_" + DateFormat2.sysdateConvertString("yyyyMMddHHmmssSSS") + "Req.txt";//请求查询执行器的文件名
                    File reqQueryFile = new File(queryReqPath + File.separator + reqQueryFileName);
                    //将校验过后的数据写入一个临时文件
                    boolean tempFileResult = generateTempFile(queryFileList, tempFile, reqQueryFileName, recvZipFileName);
                    if(tempFileResult){
                        LOGGER.debug("生成临时文件["+tempFile.getName()+"]成功，开始生成请求查询执行文件["+reqQueryFile.getName()+"]！");
                        generateQueryReqFile(tempFile, reqQueryFile);
                        //TODO 将文件移动一个成功目录。
                        return reqQueryFile;
                    }
                } catch (IOException e) {
                    LOGGER.error("生成文件发生异常！",e);
                    FileUtil2.moveFileToDirectory(requestFile, new File(errorPath), true);
                }
            }else{
                LOGGER.debug("查控申请法律文书信息文件不齐全，无法进行查询！");
                FileUtil2.moveFileToDirectory(requestFile, new File(errorPath), true);
            }
        } catch (FileNotFoundException e1){
            LOGGER.error("找不到请求文件！",e1);
        } catch (Exception e2) {
            LOGGER.error("处理请求文件异常。",e2);
        }
        return null;
    }

    public File format(File[] requestFiles) {
        return format(requestFiles[0]);
    }
*
     * 生成查询执行器文件
     * @param tempFile
     * @param queryReqFile
     * @throws IOException


    private void generateQueryReqFile(File tempFile, File queryReqFile) throws IOException{
        try {
            read = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile),ASPNConstans.ENCODE_UTF8));
            write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(queryReqFile),ASPNConstans.ENCODE_UTF8));
            String readLine = null;
            int currLine = 0;
            while(null!=(readLine=read.readLine())){
                currLine += 1;
                if(currLine<=1) continue;
                String[] strs = readLine.split(ASPNConstans.SYMBOL);
                if(Boolean.parseBoolean(strs[1])){
                    Map<String, String> strMap = SZGACommon.stringConvertMap(strs[5]);
                    StringBuilder sb = new StringBuilder();
                    sb.append(strs[0] + symbol);//lineId
                    sb.append("query" + symbol);
                    sb.append(strMap.get("customerId") + symbol);//客户号
                    if(SZGAEnums.A.getCode().equals(strs[0]) || SZGAEnums.E.getCode().equals(strs[0])){
                        sb.append(" " + symbol);//账号
                    }else{
                        sb.append(strMap.get("CXZH") + symbol);//账号
                    }
                    sb.append(strMap.get("ZTMC") + symbol);//姓名
                    sb.append("Y" + symbol);//账户信息
                    sb.append("Y" + symbol);//客户信息
                    sb.append("Y" + symbol);//存款信息
                    if(!(SZGAEnums.A.getCode().equals(strs[0]) || SZGAEnums.B.getCode().equals(strs[0]))){
                        sb.append("Y" + symbol);//交易明细
                    }else{
                        sb.append("N" + symbol);//交易明细
                    }
                    sb.append("N" + symbol);//理财产品
                    sb.append("Y" + symbol);//司法冻结信息
                    sb.append("Y" + symbol);//关联账户信息
                    sb.append("Y" + symbol);//主/子账户信息
                    if(!(SZGAEnums.A.getCode().equals(strs[0]) || SZGAEnums.B.getCode().equals(strs[0]))){
                        String mxqssj = strMap.get("MXQSSJ");//明细起始时间
                        String mxjzsj = strMap.get("MXJZSJ");//明细截至时间
                        sb.append(mxqssj+ "-" + mxjzsj);//交易明细起止时点
                    }else{
                        sb.append(" ");//交易明细起止时点
                    }
                    write.write(sb.toString() + ASPNConstans.newLine);
                }else{
                    continue;
                }
            }
            write.flush();
            write.close();
            read.close();
        } catch (Exception e) {
            throw new IOException("生成请求查询执行器文件异常！",e);
        } finally {
            if(read!=null) read.close();
            if(write!=null) write.close();
        }
    }

*
     * 生成临时文件
     * @param queryFileList
     * @param tempFile
     * @param reqQueryFileName
     * @param recvFileName
     * @return
     * @throws IOException


    private boolean generateTempFile(List<File> queryFileList,
                                     File tempFile,String reqQueryFileName,String recvFileName)throws IOException{
        try {
            String queryFileNames = "";
            for(File file : queryFileList){//
                queryFileNames += file.getName() + ";";
            }
            write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile),ASPNConstans.ENCODE_UTF8));
            //写入文件头，格式：请求查询执行器的文件名+接收到的文件名+查询文件数+查询文件名集合
            String lindHead = reqQueryFileName + ASPNConstans.SYMBOL
                    + recvFileName + ASPNConstans.SYMBOL
                    + queryFileList.size() + ASPNConstans.SYMBOL
                    + queryFileNames + ASPNConstans.newLine;
            write.write(lindHead);
            //写入文件明细数据
            int currLindId = 0;
            Iterator<String> it = checkDataMap.keySet().iterator();
            while(it.hasNext()){
                currLindId += 1;
                String dataKey = it.next();
                Map<String, String> dataMap = checkDataMap.get(dataKey);
                String queryCondition = dataMap.get("queryCondition");
                //拼接明细：currLineId + lineId +
                StringBuilder sb = new StringBuilder();
                sb.append(StringUtil.leftPad(Integer.toString(currLindId), 7, "0") + ASPNConstans.SYMBOL);//一个临时文件的lineId
                //标识，如果这个值为true，则执行查询。如果为false则不执行查询
                sb.append((StringUtil.isNullOrBlank(dataMap.get("customerId"))?false:true) + ASPNConstans.SYMBOL);
                sb.append(queryCondition + ASPNConstans.SYMBOL);
                sb.append(dataMap.get("lineId") + ASPNConstans.SYMBOL);
                sb.append(dataMap.get("CXNR") + ASPNConstans.SYMBOL);//01;02;03
                sb.append(dataMap.toString() + ASPNConstans.SYMBOL);
                write.write(sb.toString() + ASPNConstans.newLine);
                it.remove();
            }
            write.flush();
            write.close();
            return true;
        } catch (Exception e) {
            LOGGER.error("生成临时文件异常！",e);
        } finally{
            if(write!=null) write.close();
        }
        return false;
    }


*
     * 处理查控文件
     * @param fileList
     * @return


    private boolean startHandler(List<File> fileList){
        LOGGER.debug("开始处理查控文件，并读取查控文件的内容！");
        try {
            for (int i = 0; i < fileList.size(); i++) {
                File xmlFile = fileList.get(i);
                Map<String, List<Map<String, String>>> xmlInfoMap = ReadXmlFile.readXmlFileAttr(xmlFile);
                //查询请求基本数据项
                List<Map<String, String>> basicList = xmlInfoMap.get("basicList");
                Map<String, String> basicMap = basicList.get(0);
//				//查询人数据项
//				List<Map<String, String>> queryPersonList = xmlInfoMap.get("queryPersonList");
                //查询主体数据项
                List<Map<String, String>> queryMainList = xmlInfoMap.get("queryMainList");
//				//获取法律文书内容
//				List<Map<String, String>> wsinfoList = xmlInfoMap.get("wsinfoList");
                String qqcslx = DictCodeSZGA.getQueryType(basicMap.get("QQCSLX"));//请求措施类型01-常规查询
                String mbjgdm = basicMap.get("MBJGDM");//目标机构代码
                String ztlb = basicMap.get("ZTLB");
                if("01".equals(qqcslx) && DictCodeSZGA.bosCode2.equals(mbjgdm)){//目标机构代码
                    //开始账户验证
                    try {
                        CountDownLatch countDown = new CountDownLatch(queryMainList.size());
                        Semaphore semaphore = new Semaphore(3);
                        ExecutorService executor = Executors.newFixedThreadPool(10);
                        //循环这个集合-查询主体数据项
                        for(int j=0;j<queryMainList.size();j++){
                            Map<String, String> dataInfo = queryMainList.get(j);
                            //添加查控主体类别至集合：01：对私-个人；02：对公-单位
                            dataInfo.put("ZTLB", ztlb);
                            //执行查询操作
                            executor.execute(new QueryCustomerInfo(countDown, semaphore, dataInfo));
                        }
                        countDown.await();
                        executor.shutdown();
                    } catch (Exception e) {
                        LOGGER.error("执行查询客户信息异常！",e);
                    }
                }else{
                    LOGGER.debug("当前措施类型["+qqcslx+"]，目标结构代码["+mbjgdm+"]，暂不支持！");
                    continue;
                }
            }
        } catch (Exception e) {
            LOGGER.error("处理查控文件，并读取查控文件的内容异常！",e);
            return false;
        }
        LOGGER.debug("处理查控文件，并读取查控文件的内容结束！");
        return true;
    }

*
     * 查询客户信息，根据证件号码+证件类型查询
     * 根据账卡号查询
     * @author huangcan
     * @date created in 2019年7月22日 下午2:13:03


    private class QueryCustomerInfo implements Runnable{
        private CountDownLatch countDown;
        private Semaphore semaphore;
        private Map<String, String> dataInfo;

        public QueryCustomerInfo(CountDownLatch countDown, Semaphore semaphore, Map<String, String> dataInfo) {
            super();
            this.countDown = countDown;
            this.semaphore = semaphore;
            this.dataInfo = dataInfo;
        }

        public void run() {
            try {
                try {
                    semaphore.acquire();
                    LOGGER.debug("申请资源成功！！");
                } catch (InterruptedException e) {
                    LOGGER.error("申请查询客户信息资源异常！",e);
                }
                String ztlb = dataInfo.get("ZTLB");//查询主体--对公或者对私
                String cxfs = dataInfo.get("CXFS");//01;02;03--查询客户号
                String zzlx = dataInfo.get("ZZLX");//证照类型
                String zzhm = dataInfo.get("ZZHM");//证照号码
                String cxzh = dataInfo.get("CXZH");//查询账号
                //查询条件-查询内容-查询方式
                String queryCondition = dataInfo.get("queryCondition");
                if("01".equals(ztlb)){//对私
                    if(SZGAEnums.A.getCode().equals(queryCondition) || SZGAEnums.E.getCode().equals(queryCondition)){
                        List<BOSCustomerInfo> customerInfoList = ServiceCommon.queryCustomerInfo(zzhm, DictCodeSZGA.getIdTypeT24(zzlx), false, null);
                        if(customerInfoList!=null && customerInfoList.size()>0){
                            BOSCustomerInfo customerInfo = customerInfoList.get(0);
                            if(customerInfo.isOurCustomer()){
                                //我行的客户，查询这个客户号下的所有账号信息
                                if("01".equals(cxfs)){
                                    String customerName = customerInfo.getCustomerName();
                                    String ztmc = dataInfo.get("ZTMC");
                                    if(!StringUtil.isNullOrBlank(ztmc) && ztmc.equals(customerName)){
                                        dataInfo.put("customerId", customerInfo.getCustomerId());
                                    }
                                }else if("02".equals(cxfs)){
                                    dataInfo.put("customerId", customerInfo.getCustomerId());
                                }
                            }
                        }
                    }else if(SZGAEnums.B.getCode().equals(queryCondition) || SZGAEnums.D.getCode().equals(queryCondition) || SZGAEnums.F.getCode().equals(queryCondition)){
                        String customerId = ServiceCommon.queryCustomerIdByAcctNo(cxzh);//客户号
                        dataInfo.put("customerId", customerId);
                    }
                    //校验结束，将这个数据添加至map集合
                    checkDataMap.put(dataInfo.get("lineId"), dataInfo);
                }else if("02".equals(ztlb)){//对公
                    if("01".equals(cxfs)){//按证照类型+证照号码+主体名称--查询

                    }else if("02".equals(cxfs)){//证照类型+证照号码--查询

                    }else if("03".equals(cxfs)){//按主体名称--查询

                    }
                    checkDataMap.put(dataInfo.get("lineId"), dataInfo);
                }else{
                    LOGGER.debug("当前查询主体类别["+ztlb+"]错误");
                }
            } catch (Exception e) {
                LOGGER.error("",e);
            } finally{
                try {
                    countDown.countDown();
                    semaphore.release();
                } catch (Exception e2){}
            }
        }
    }

}
*/
